import Vue from 'vue'
// 全局配置
import settings from './settings.js'

function computedBaseUrl(url) {
	return (url.indexOf('http') === -1 ? settings.baseUrl : '') + url
}

// 发送请求
export default (options) => {
	const {
		url = '',
			method = 'GET',
			data = {},
			header = {}
	} = options
	return new Promise((resolve, reject) => {
			try {
				uni.request({
					url: computedBaseUrl(url),
					method,
					data,
					header: {
						// "Content-Type": "multipart/form-data",
						"token": uni.getStorageSync('token'),
						...header
					},
					success(e) {
						if (e.data.code == 401) {
							uni.showToast({
								title: '登录失效',
								icon: 'none'
							})
							uni.removeStorageSync('token');
							return uni.reLaunch({url:"/pages/login/login"});
						}
						resolve(e.data)
					},
					fail(e) {
						reject({
							...e,
							msg: e.errMsg || e.msg || '未知错误'
						})
					}
				})
			} catch (err) {
				reject({
					...err,
					msg: err.errMsg || err.msg || '未知错误'
				})
			}
		}).then(data => data)
		.catch(err => err)
}